import { createStore } from "redux";

// 初始值
const initSate = {
  // 首页列表
  list: [],
  /**
   * @desc 购物车每一项
   * @param { id }    String 数据唯一标识
   * @param { image } String 图片路径
   * @param { title } String 标题
   * @param { desc }  String 描述
   * @param { price } Number 单价
   * @param { oldPrice } String 老价钱
   * @param { sell } String 销售量
   * @param { count } Number 数量
   * @param { state } Number 选中状态
   * */

  // 3   1
  carList: JSON.parse(localStorage.getItem("carList")) || [],
};
// 纯函数
const reduce = (state = initSate, action) => {
  switch (action.type) {
    // 修改 list action
    case "setList":
      return {
        ...state,
        list: action.payload,
      };
    // 加入购物车
    case "addToCar": {
      // 验证商品是否存在购物车
      const shop = state.carList.find((v) => v.id === action.payload.id);
      // 存在 数量++
      if (shop) shop.count++;
      // 不存在  添加新数据
      else state.carList.push(action.payload);

      console.log(state.carList);
      // localStorage.setItem('carList', JSON.stringify(state.carList))
      return {
        ...state,
        carList: [...state.carList],
      };
    }
    // 减少购物车
    case "subToCar": {
      // 验证商品是否存在购物车
      const shop = state.carList.find((v) => v.id === action.payload.id);
      // 存在 数量++
      if (shop) shop.count--;
      // 不存在  添加新数据

      console.log(state.carList);
      // localStorage.setItem('carList', JSON.stringify(state.carList))
      return {
        ...state,
        carList: [...state.carList],
      };
    }
     // 切换状态购物车
    case "switchState": {
      // 验证商品是否存在购物车
      const shop = state.carList.find((v) => v.id === action.payload.id);
      // 切换
      if (shop) shop.state = !shop.state;


      console.log(state.carList);
      // localStorage.setItem('carList', JSON.stringify(state.carList))
      return {
        ...state,
        carList: [...state.carList],
      };
    }
  }

  return state;
};

// 创建仓库
const store = createStore(reduce);

// 监听 dispatch action
store.subscribe(() => {
  const { carList } = store.getState();
  localStorage.setItem("carList", JSON.stringify(carList));
});

export default store;
